﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Xml.Linq;

namespace process_monitor.Controller
{
    internal class MiniController
    {
        public static void WriteLog(string strLog)
        {
            //文件所在路径
            string sFilePath = Application.StartupPath.ToString() + "\\log\\" + DateTime.Now.ToString("yyyyMM");
            //文件名称
            string sLogFileName = "log" + DateTime.Now.ToString("dd") + ".log";
            string sFileName = sFilePath + "\\" + sLogFileName; //文件的绝对路径
            if (!Directory.Exists(sFilePath))//验证路径是否存在
            {
                Directory.CreateDirectory(sFilePath);
                //不存在则创建
            }
            FileStream fs;
            StreamWriter sw;
            if (File.Exists(sFileName))
            //验证文件是否存在，有则追加，无则创建
            {
                FileInfo fileinfo = new FileInfo(sFileName);
                //获取指定目录下的所有的子文件
                string[] files = Directory.GetFiles(sFilePath, sLogFileName + "*", SearchOption.TopDirectoryOnly);
                if (fileinfo.Length > 2 * 1024 * 1024)
                {
                    File.Move(sFileName, GetPathStr(sFilePath, string.Format("{0}.log", DateTime.Now.ToString("dd-HH-mm-ss"))));

                    if (!File.Exists(sFileName))
                    {
                        using (File.Create(sFileName)) { }
                    }
                }
                fs = new FileStream(sFileName, FileMode.Append, FileAccess.Write);
            }
            else
            {
                fs = new FileStream(sFileName, FileMode.Create, FileAccess.Write);
            }
            sw = new StreamWriter(fs);
            sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + "   ---   " + strLog);
            sw.Close();
            fs.Close();

            //DeleteFile(sFilePath, 30);
            DeleteDirectory(Application.StartupPath.ToString() + "\\log\\", 90);

        }
        public static string HOE_L = "\r\n             ";

        /// <summary>
        /// 拼接地址串
        /// </summary>
        /// <param name="firstPath"></param>
        /// <param name="secondPath"></param>
        /// <returns></returns>
        private static string GetPathStr(string firstPath, string secondPath)
        {
            StringBuilder builder = new StringBuilder();

            builder.Append(firstPath);
            builder.Append("\\");
            builder.Append(secondPath);
            return builder.ToString();
        }

        private static void CleanFile(string folderPath)
        {
            //string path = AppDomain.CurrentDomain.BaseDirectory + @"\log\";
            string path = folderPath;
            DirectoryInfo dir = new DirectoryInfo(path);
            FileInfo[] files = dir.GetFiles();
            foreach (FileInfo file in files)
            {
                if (file.LastWriteTime < DateTime.Now.AddDays(-10))
                {
                    file.Delete();
                    Form1.form.outPut("已删除日志文件：" + file.FullName);
                }
            }
        }

        private static void DeleteFile(string fileDirect, int saveDay)
        {
            DateTime nowTime = DateTime.Now;//获取当前时间
            string[] files = Directory.GetFiles(fileDirect, "*.*", SearchOption.AllDirectories); //获取该目录下所有文件
            foreach (string file in files)
            {
                FileInfo fileInfo = new FileInfo(file);//获取文件目录
                TimeSpan t = nowTime - fileInfo.CreationTime; //当前时间 减去 文件创建时间
                int day = t.Days;
                if (day > saveDay) //保存的时间 ； 单位：天
                {
                    File.Delete(file); //删除超过时间的文件
                    Form1.form.outPut("已删除日志文件：" + file);
                }
            }
        }

        public static void DeleteDirectory(string fileDirect, int saveDay)
        {
            DateTime nowTime = DateTime.Now;//获取当前时间
            DirectoryInfo root = new DirectoryInfo(fileDirect);//获取文件夹目录
            DirectoryInfo[] dics = root.GetDirectories();//获取该目录下所有文件夹
            FileAttributes attr = File.GetAttributes(fileDirect);//获取文件格式
            if (attr == FileAttributes.Directory)//判断是不是文件夹
            {
                foreach (DirectoryInfo file in dics)//遍历文件夹
                {
                    TimeSpan t = nowTime - file.CreationTime; //当前时间 减去 文件创建时间
                    int day = t.Days;
                    if (day > saveDay) //保存的时间 ； 单位：天
                    {
                        Directory.Delete(file.FullName, true); //删除超过时间的文件夹
                        Form1.form.outPut("已删除日志文件夹：" + file.FullName);
                    }
                }
            }

        }

        /// <summary>
        /// 判断进程是否在运行
        /// </summary>
        /// <param name="processName"></param>
        /// <returns></returns>
        public static bool IsProcessRunning(string processName)
        {
            /*
            Process[] processes = Process.GetProcessesByName(processName);
            return processes.Length > 0;
            */
            var res = false;
            if (Process.GetProcessesByName(processName).ToList().Count > 0)
            {
                res = true;
            }
            return res;
        }

        /// <summary>
        /// 运行进程
        /// </summary>
        /// <param name="processName"></param>
        public static void StartProcess(string processName)
        {
            try
            {
                Process.Start(processName);
            }
            catch (Exception ex)
            {
                Form1.form.outPut($"启动软件失败 {processName}: {ex.Message}");
            }
        }
        
        /// <summary>
        /// 获得进程名称
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static string getProcessName(string filePath)
        {
            string fileName = Path.GetFileNameWithoutExtension(filePath);
            return fileName;
        }

        /// <summary>
        /// 结束进程
        /// </summary>
        /// <param name="processName"></param>
        public static void killProcess(string processName)
        {
            // 尝试结束指定名称的进程
            try
            {
                Process[] processes = Process.GetProcessesByName(processName);
                foreach (Process process in processes)
                {
                    process.Kill();
                    Form1.form.outPut($"{processName} 已终止。");
                }
            }
            catch (Exception ex)
            {
                Form1.form.outPut($"终止进程失败 {processName}: {ex.Message}");
            }
        }

        /// <summary>
        /// 重启进程
        /// </summary>
        /// <param name="processName"></param>
        public static void restartProcess(string processName)
        {
            killProcess(processName);
            Thread.Sleep(TimeSpan.FromSeconds(2));
            StartProcess(processName);
        }
    }
}
